from django.db import transaction
from rest_framework import serializers
from goods.models import SKU, SKUSpecification
from celery_tasks.detail.tasks import generate_detail_html


class SkuSpecSerializer(serializers.Serializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()


class SkuModelSerializer(serializers.ModelSerializer):
    spu = serializers.StringRelatedField(read_only=True)
    category = serializers.StringRelatedField(read_only=True)
    spu_id = serializers.IntegerField()
    category_id = serializers.IntegerField()

    specs = SkuSpecSerializer(many=True)

    class Meta:
        model = SKU
        fields = '__all__'

    def create(self, validated_data):
        specs = validated_data.pop('specs')
        with transaction.atomic():
            sid = transaction.savepoint()
            try:

                sku = super().create(validated_data)
                for item in specs:
                    item['sku_id'] = sku.id

                    SKUSpecification.objects.create(**item)
            except:
                transaction.savepoint_rollback(sid)
                raise serializers.ValidationError('创建库存商品失败')
            else:
                transaction.savepoint_commit(sid)

                generate_detail_html.delay(sku.id)

                return sku

    def update(self, instance, validated_data):

        specs = validated_data.pop('specs')
        with transaction.atomic():
            sid = transaction.savepoint()
            try:
                instance = super().update(instance, validated_data)
                SKUSpecification.objects.filter(sku_id=instance.id).delete()

                for item in specs:
                    item['sku_id'] = instance.id
                    SKUSpecification.objects.create(**item)
            except:
                transaction.savepoint_rollback(sid)
                raise serializers.ValidationError('修改sku失败')
            else:
                transaction.savepoint_commit(sid)

                generate_detail_html.delay(instance.id)
            return instance


class SkuSimpleSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField()



